library(readstata13)
library(tidyverse)
library(fixest)
library(readxl)
library(broom)
library(ggthemes)
library(modelsummary)
library(plm)

if(!require('data.table')) {
  install.packages('data.table')
  library('data.table')
}
directory = c("~/Dropbox (Harvard University)/Coursework/Harvard/2022 Fall/Gov 2001/Climate conflict/")
nd_conflict <- read.dta13(paste0(directory[1],"data/clean/climate_conflict_panel.dta")) %>%
  filter(year>2000)   %>%
  filter(year<2010) 


setFixest_dict(c(anyconflict_1y = "1 year", anyconflict_3y = "3 years",
                 anyconflict_5y = "5 years", anynatdis = "Any natural disaster",
                 country = "Country", year="Year"))
conflict_est <- feols(c(anyconflict_1y, anyconflict_3y,anyconflict_5y)
                         ~ anynatdis | country[year] + year, 
                         data = nd_conflict) %>% 
  as.list()

#Data by continent
nd_c_Africa <- nd_conflict %>%
  filter(region=="Africa")
nd_c_America <- nd_conflict %>%
  filter(region=="Americas")
nd_c_Asia <- nd_conflict %>%
  filter(region=="Asia")
nd_c_Europe <- nd_conflict %>%
  filter(region=="Europe")
nd_c_Oceania <- nd_conflict %>%
  filter(region=="Oceania")

#  & \multicolumn{3}{c}{Any conflict in the following}\\
etable(conflict_est, file= paste0(directory[1],"/output/tables/FEmodels_v1.tex"), 
       style.tex = style.tex("aer"), fitstat = ~ r2 + n, replace=TRUE, headers = c("Any conflict in the following"))

africa_est <- feols(anyconflict_3y ~ anynatdis | country[year] + year, 
                      data = nd_c_Africa) 
america_est <- feols(anyconflict_3y ~ anynatdis | country[year] + year, 
                    data = nd_c_America) 
asia_est <- feols(anyconflict_3y ~ anynatdis | country[year] + year, 
                     data = nd_c_Asia) 
europe_est <- feols(anyconflict_3y ~ anynatdis | country[year] + year, 
                     data = nd_c_Europe) 
oceania_est <- feols(anyconflict_3y ~ anynatdis | country[year] + year, 
                     data = nd_c_Oceania) 
conflict_region<-list(africa_est, america_est, asia_est, europe_est, oceania_est)
setFixest_dict(c(anyconflict_3y = "Any conflict in the following 3 years", anynatdis = "Any natural disaster",
                 country = "Country", year="Year"))
etable(conflict_region, file= paste0(directory[1],"/output/tables/FEmodels_regions.tex"), 
       style.tex = style.tex("aer"), fitstat = ~ r2 + n, replace=TRUE, headers = c("Africa", "America", "Asia", "Europe", "Oceania"))


# FE recover constant

conflict_3y <- feols(anyconflict_3y
                      ~ anynatdis | country[year] + year, 
                      data = nd_conflict)

conflict_3y_FE <- fixef(conflict_3y)

